import service from '../../api/service'
import * as Constant from '../../utils/constant'
import { ALERT } from '../../utils/responseHandle'
import { CacheUtil } from '../../utils/cacheUtil'
// initial state
const state = {
  auth: {
    check () {
      return this.access_token !== null && this.access_token !== '' && this.access_token !== 'undefined' && this.access_token !== undefined
    },
    access_token: CacheUtil.getSesstionStorage(Constant.AUTH_ACCESS_TOKEN)
  },
  libname: undefined,
  secret: undefined,
  serviceid: undefined,
  loadLibInfo: {
    libname: undefined,
    libaccount: undefined
  }
}

// getters
const getters = {}

// actions
const actions = {
  doLogin ({ state, commit, dispatch }, { _this, data }) {
    service.getToken(response => {
      if (response.status === 200) {
        let rpd = response.data
        commit(Constant.ACCOUNT_AUTH_STATUS_CHANGED, {_this, rpd, data: data})
      } else {
        ALERT.error('用户名或密码错误')
      }
    }, data, state.serviceid, state.secret)
  }
}

// mutations
const mutations = {
  ACCOUNT_AUTH_STATUS_CHANGED (state, {_this, rpd, data}) {
    if (rpd.access_token) {
      CacheUtil.setLocalStorage(Constant.AUTH_ACCESS_TOKEN, rpd.access_token)
      CacheUtil.setLocalStorage(Constant.LOGIN_NAME, rpd.organization)
      CacheUtil.setLocalStorage(Constant.CODEWORD, data.password)
      state.auth.access_token = rpd.access_token
      _this.$router.push('/')
    } else {
      state.auth.access_token = null
    }
  }
}

export default {
  namespaced: true,
  state,
  getters,
  actions,
  mutations
}
